import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { message } from 'ant-design-vue'
import { userStore } from '@/store/modules/user'
import getSessionContextDTO from '@/api/sessionContext'
import { AxiosCanceler } from './axiosCancel'

const axiosCanceler = new AxiosCanceler()

export const uploadImgAddress = '/api/tenant/manager/package/uploadFile'

// 401 token失效
export const tokenInvalid = function (res: any) {
  if (res.code == '401') {
    const userModule = userStore()
    userModule.resetToken()
    message.error({
      content: '登录态失效，请重新登录',
      duration: 5
    })
    setTimeout(() => {
      location.reload() // To prevent bugs from vue-router
    }, 1000)
  } else {
    message.error({
      content: res.message || '上传失败',
      duration: 3
    })
  }
}

const service = axios.create({
  baseURL: '',
  timeout: 0,
  withCredentials: true
})

// Request interceptors
service.interceptors.request.use(
  (config: any) => {
    const userModule = userStore()
    if (userModule.token) {
      config.headers['Authorization'] = userModule.token
    }
    axiosCanceler.addPending(config)
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

// Response interceptors
service.interceptors.response.use(
  (response) => {
    const res = response.data
    const userModule = userStore()
    axiosCanceler.removePending(response.config)
    if (res.code !== '200') {
      if (res.code == '401') {
        userModule.resetToken()
        message.error({
          content: '登录态失效，请重新登录',
          duration: 5
        })
        setTimeout(() => {
          location.reload()
        }, 1000)
      } else {
        message.error({
          content: res.message || '数据异常',
          duration: 5
        })
      }
      return Promise.reject(res)
    } else {
      return res
    }
  },
  (error) => {
    let msg = ''
    if (error && error.response) {
      if (error.message === 'Network Error') {
        msg = '本地网络异常，请检查网络后重试'
      } else if (error.message.includes('timeout')) {
        msg = '系统接口请求超时'
      } else if (error.message && error.message.includes('Request failed with status code')) {
        msg = '系统接口' + error.message.substr(error.message.length - 3) + '异常'
      }
      message.error({
        content: msg || error.message,
        duration: 5
      })
    }
    return Promise.reject(error)
  }
)

export default function request(options: any) {
  let { data, url, method = 'get' } = options
  if (method.toUpperCase() === 'GET') {
    options.params = data
  }
  return service(options)
}

function exportData(filename: string, blob: any) {
  let navigator = window.navigator as any
  if (typeof navigator.msSaveBlob !== 'undefined') {
    navigator.msSaveBlob(blob, filename)
  } else {
    let blobURL = window.URL.createObjectURL(blob)
    let tempLink = document.createElement('a')
    tempLink.style.display = 'none'
    tempLink.href = blobURL
    tempLink.setAttribute('download', filename)
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank')
    }
    document.body.appendChild(tempLink)
    tempLink.click()
    document.body.removeChild(tempLink)
    window.URL.revokeObjectURL(blobURL)
  }
}

export function downExcel(url: string, params: any, name: string, method = 'POST') {
  name = name || new Date().getTime() + ''
  const userModule = userStore()
  let config: any = {
    // baseURL: 'https://api.example.com',
    method: method,
    url: url, // 请求地址
    data: params, // 参数
    // headers: { 'Content-Type': 'multipart/form-data' },
    headers: {
      Authorization: userModule.token
    },
    responseType: 'blob' // 表明返回服务器返回的数据类型
  }
  return axios(config).then((res: AxiosResponse<any>) => {
    // 处理返回的文件流
    if (res && res.data && res.data.type === 'application/json') {
      const content: any = res.data
      const blob = new Blob([content], {
        type: 'application/json;charset=utf-8'
      })
      const reader = new FileReader()
      reader.onload = function (event) {
        const content = reader.result //内容就在这里
        if (content) {
          const result = JSON.parse(content.toString())
          if (result.code === '401') {
            userModule.resetToken()
            message.error({
              content: '登录态失效，请重新登录',
              duration: 5
            })
            location.reload()
          } else {
            message.error({
              content: result.message || '未知错误',
              duration: 5
            })
          }
        }
      }
      reader.readAsText(blob)
      return
    }
    try {
      const content: any = res.data
      const blob = new Blob([content], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' // application/pdf 'text/csv
      })
      const filename = `${name}.xlsx`
      exportData(filename, blob)
      return Promise.resolve()
    } catch (err) {
      return Promise.reject()
    }
  })
}
// 获取图片流
export function getImg(url: string, params: any, method = 'POST') {
  // let data = { ...(params || {}), ...getSessionContextDTO() }
  let data = { ...(params || {}) }
  let config: any = {
    method: method,
    url: url, // 请求地址
    data, // 参数
    responseType: 'blob' // 表明返回服务器返回的数据类型
  }
  return axios(config).then((res: AxiosResponse<any>) => {
    try {
      const content: any = res.data
      const blob = new Blob([content])
      return Promise.resolve(window.URL.createObjectURL(blob))
    } catch (err) {
      return Promise.reject()
    }
  })
}

// 上传文件
export function getUploadFile(params: any, url = uploadImgAddress) {
  const userModule = userStore()
  return axios
    .post(url, params, {
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: userModule.token
      }
    })
    .then((response: AxiosResponse<any>) => {
      try {
        const res = response.data
        if (res.code !== '200') {
          message.error({
            content: res.message || '数据异常',
            duration: 5
          })
          return Promise.reject(res)
        } else {
          return res
        }
      } catch (error: any) {
        let msg = ''
        if (error && error.response) {
          switch (error.response.status) {
            default:
              msg = '系统接口异常，请稍后再试'
          }
          message.error({
            content: msg || error.message,
            duration: 5
          })
        }
        return Promise.reject(error)
      }
    })
}
